package com.sgb.kjwl.view.ui.activity.manage

import android.content.Context
import android.content.Intent
import android.view.View
import androidx.databinding.DataBindingUtil
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.scwang.smart.refresh.layout.api.RefreshLayout
import com.scwang.smart.refresh.layout.listener.OnRefreshLoadMoreListener
import com.scwang.smart.refresh.layout.listener.ScrollBoundaryDecider
import com.sgb.kjwl.AppActivity
import com.sgb.kjwl.R
import com.sgb.kjwl.databinding.ActivityTenderInviteBiddingBinding
import com.sgb.link.entity.PickInvitedApply
import com.sgb.zhaocai.view.activity.PickInvitedApplyDetailsActivity
import com.sgb.zhaocai.view.adapter.PickInvitedApplyAdapter
import com.sgb.kjwl.viewmodel.manage.WebsiteContractListViewModel
import com.swgk.core.BaseAppHelper
import com.swgk.core.recyclerview.decoration.RecyclerCustomDecoration
import com.swgk.core.util.MToast
import com.swgk.core.util.SharedPreferenceUtil
import java.util.*

/**
 * 招采--报名、竞价
 */
class TenderInviteBiddingActivity : AppActivity() {

    private lateinit var mViewModel : WebsiteContractListViewModel
    private lateinit var mBinding : ActivityTenderInviteBiddingBinding

    private var mIsInvite = true //是否是邀请报名 否则 邀请竞价

    private var isLoadMore = false //是否加载更多
    private var isEnableLoadMore = false//是否能加载更多

    private lateinit var mAdapter: PickInvitedApplyAdapter

    private var mWebsiteNo = ""

    private val companyList  = ArrayList<String>()
    private val companyNameList = ArrayList<String>()

    private var mPickInvitedApply : PickInvitedApply?= null

    companion object{
        const val KEY_IS_INVITE = "key_is_invite"
        const val KEY_WEBSITE_NO = "key_website_no"
        fun launch(context: Context, isInvite : Boolean, websiteNo : String){
            val intent = Intent()
            intent.setClass(context, TenderInviteBiddingActivity::class.java)
            intent.putExtra(KEY_IS_INVITE, isInvite)
            intent.putExtra(KEY_WEBSITE_NO, websiteNo)
            context.startActivity(intent)
        }
    }

    override fun init() {
        super.init()
        isLoadMore = false
        getData()
    }

    fun getData(){
        if (mIsInvite){
            mViewModel.findSignPage(isLoadMore)
        } else {
            mViewModel.getFindBidPage(isLoadMore)
        }
    }

    override fun initView() {
        super.initView()
        if (intent != null){
            mIsInvite = intent.getBooleanExtra(KEY_IS_INVITE, true)
            mWebsiteNo = intent.getStringExtra(KEY_WEBSITE_NO)
        }
        mViewModel = ViewModelProvider.AndroidViewModelFactory.getInstance(BaseAppHelper.get().instance).create(
            WebsiteContractListViewModel::class.java)
        mBinding = DataBindingUtil.setContentView(this, R.layout.activity_tender_invite_bidding)
        mBinding.include.titleView.text = if (mIsInvite) "投标列表" else "邀请竞价"
        mBinding.include.ivBack.setOnClickListener { finish() }
        //mBinding.emptyView.findViewById<TextView>(R.id.no_data_tv).text = "功能升级中"
        initRecyclerView()
        mViewModel.pickInvitedApplyList.observe(this, {
            isEnableLoadMore = it != null && it.size >= 10
            if (isLoadMore){
                mAdapter.addDatas(it)
            } else {
                if (it.isEmpty()){
                    mBinding.emptyView.visibility = View.VISIBLE
                    mBinding.recycleView.visibility = View.GONE
                } else {
                    mBinding.emptyView.visibility = View.GONE
                    mBinding.recycleView.visibility = View.VISIBLE
                    mAdapter.datas = it
                }
            }
        })
        mViewModel.pickInvitedBiddingList.observe(this, {
            isEnableLoadMore = it != null && it.size >= 10
            if (isLoadMore){
                mAdapter.addDatas(it)
            } else {
                if (it.isEmpty()){
                    mBinding.emptyView.visibility = View.VISIBLE
                    mBinding.recycleView.visibility = View.GONE
                } else {
                    mBinding.emptyView.visibility = View.GONE
                    mBinding.recycleView.visibility = View.VISIBLE
                    mAdapter.datas = it
                }
            }
        })
        mViewModel.isEnableInvite.observe(this, {
            if (it && mPickInvitedApply != null){
                companyList.clear()
                companyList.add(mWebsiteNo)
                companyNameList.clear()
                companyNameList.add(mPickInvitedApply!!.companyName)
                PickInvitedApplyDetailsActivity.start(
                    this,
                    if (mIsInvite) "1" else "2",
                    mPickInvitedApply!!.name,
                    mPickInvitedApply!!.applyEndTime,
                    0,
                    companyList,
                    mPickInvitedApply!!.id,
                    ArrayList(),
                    companyNameList,
                    ArrayList(),
                    0,
                    "1"
                )
            } else {
                MToast.showToast(this, "当前企业不可以邀请")
            }
        })
    }

    private fun initRecyclerView() {
        // SwipeRefreshLayout 刷新
        mBinding.refreshLayout.setOnRefreshLoadMoreListener(object : OnRefreshLoadMoreListener {
            override fun onLoadMore(refreshLayout: RefreshLayout) {
                isLoadMore = true
                getData()
                mBinding.refreshLayout.finishLoadMore(500)
            }

            override fun onRefresh(refreshLayout: RefreshLayout) {
                isLoadMore = false
                getData()
                mBinding.refreshLayout.finishRefresh(500)
            }
        })
        //解决 在实现 上拉加载更多 和 下拉刷新 时  遇到item不在顶端就执行了刷新的方法和数据item没有填满屏幕也执行了加载更多
        mBinding.refreshLayout.setScrollBoundaryDecider(object : ScrollBoundaryDecider {
            override fun canRefresh(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                return mBinding.recycleView.computeVerticalScrollOffset() === 0
            }

            override fun canLoadMore(content: View): Boolean {
                if (mBinding.recycleView == null) return false
                //整个View控件的高度
                val scrollRange: Int = mBinding.recycleView.computeVerticalScrollRange()
                //当前屏幕之前滑过的距离
                val scrollOffset: Int = mBinding.recycleView.computeVerticalScrollOffset()
                //当前屏幕显示的区域高度
                val scrollExtent: Int = mBinding.recycleView.computeVerticalScrollExtent()
                //获取recyclerView的高度
                val height: Int = mBinding.recycleView.height
                if (height > scrollRange) {
                    return false
                }
                return isEnableLoadMore && scrollRange <= scrollOffset + scrollExtent
            }
        })
        mBinding.recycleView.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        mBinding.recycleView.setItemViewCacheSize(100)
        mBinding.recycleView.setHasFixedSize(true)
        mAdapter =
            PickInvitedApplyAdapter(this, null)
        mBinding.recycleView.adapter = mAdapter
        mAdapter.setFromWhere(if (mIsInvite) "1" else "2")
        mBinding.recycleView.addItemDecoration(
            RecyclerCustomDecoration(
                0f,
                0f,
                0f,
                resources.getDimension(R.dimen.dp10), resources.getColor(R.color.color_main_bg)
            )
        )

        mAdapter.onIChildClick(PickInvitedApplyAdapter.IChildClick { pickInvitedApply ->
                mPickInvitedApply = pickInvitedApply
                mViewModel.websiteIsEnableInvite(pickInvitedApply.id, if (mIsInvite) "1" else "2",
                    SharedPreferenceUtil.getInstance().getSaveStringData(SharedPreferenceUtil.COMPANY_NO, "") , mWebsiteNo)
        })
    }

    override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
        //super.onActivityResult(requestCode, resultCode, data)
    }
}